﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xyz.Framework.Server.DataAcessLayer;
using Xyz.Enterprise.Server.DomainObjects;
using Xyz.Enterprise.Shared.DataContracts.DataObjects;
using Xyz.Enterprise.Shared.Utils;
using System.Data.Objects;
using Xyz.Framework.Server.Caching;


namespace Xyz.Enterprise.Server.BusinessLogics
{
    public class EnterpriseLayerBL
    {
        public static CityDTO[] GetCities()
        {
            CityDTO[] _cacheresult =  (CityDTO[])Cache.Current.Get(EnterpriseCacheKeys.CITY_CACHE_KEY);
            if (_cacheresult != null)
                return _cacheresult;
            using (DataBaseContext db = new DataBaseContext(ConnectionStringUtility.CONNECTION_STRING, ConnectionStringUtility.CONTAINER_NAME))
            {
                ObjectSet<City> _citySet = db.CreateObjectSet<City>();
                ObjectSet<Town> _townSet = db.CreateObjectSet<Town>();


                var _result = (from c in _citySet
                               join t in _townSet on c.Id equals t.CityId into towns
                               //from town in towns.DefaultIfEmpty()
                               select new
                               {
                                   Name = c.Name,
                                   CityCode = c.CityCode,
                                   Towns = towns,
                                   //Town

                               }).ToArray();

                List<CityDTO> _cities = new List<CityDTO>();
                if (_result.Length > 0)
                {
                    foreach (var item in _result)
                    {
                        CityDTO _city = new CityDTO();
                        _city.CityCode = item.CityCode;
                        _city.Name = item.Name;
                        if (item.Towns.Count() > 0)
                        {
                            _city.Towns = (from x in item.Towns
                                           select new TownDTO
                                           {
                                               Name = x.Name,
                                               TownCode = x.TownCode,
                                           }).ToArray();
                        }
                        _cities.Add(_city);
                    }
                }
                CityDTO[] cacheresult = (CityDTO[])Cache.Current.Get(EnterpriseCacheKeys.CITY_CACHE_KEY);
                if (cacheresult == null)
                    Cache.Current.Set(EnterpriseCacheKeys.CITY_CACHE_KEY, _cities.ToArray());
                return _cities.ToArray();
            }
        }

        public static void ResetCityCache()
        {
            Cache.Current.Remove(EnterpriseCacheKeys.CITY_CACHE_KEY);
        }
    }
}
